package com.jizhi.onework.service.impl;

import com.jizhi.onework.dao.UserMapper;
import com.jizhi.onework.dataobj.dto.UserDTO;
import com.jizhi.onework.dataobj.vo.UserVO;
import com.jizhi.onework.framework.model.ServiceResponse;
import com.jizhi.onework.framework.shiro.service.PasswordService;
import com.jizhi.onework.pojo.User;
import com.jizhi.onework.service.UserService;
import com.jizhi.onework.utils.SaltUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户业务实现类
 *
 * @author hzhang7
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordService passwordService;

    @Override
    public ServiceResponse<UserVO> getUserById(Long userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return new ServiceResponse<>(false, null, "用户不存在");
        }
        return new ServiceResponse<>(true, new UserVO(user), null);
    }

    @Override
    public ServiceResponse<UserVO> selectUserByPhoneNumber(String username) {
        return null;
    }

    @Override
    public ServiceResponse<UserVO> registerUser(UserDTO userDTO) {
        // 注册信息逻辑验证

        User userDO = userDTO.toDO();
        // 设置随机盐
        userDO.setSalt(SaltUtil.randomSalt());
        // 构建密码
        String password = passwordService.encryptPassword(userDO.getPhone(), userDO.getPassword(), userDO.getSalt());
        userDO.setPassword(password);
        userMapper.insert(userDO);
        if (userDO.getId() == null) {
            return new ServiceResponse<>(false, null, "注册用户失败, 请联系管理员");
        }
        userDO = userMapper.selectByPrimaryKey(userDO.getId());
        return new ServiceResponse<>(true, new UserVO(userDO), null);
    }
}
